import { IGNORE_AUTH_ROUTES, IGNORE_PERMISSION_ROUTES, NOT_FOUND_ROUTER } from "@/config/routerConstant";
import { ROLE_MENU_KEY, TOKEN_SESSION_KEY } from "@/config/tokenConstant";
import { RoleMenuVO } from "@/pojo/RoleMenuVO";
import type { Router } from "vue-router";

export function useRouterGuard(router: Router) {
  /***
   * 全局前置守卫
   */
  router.beforeEach((to, from, next) => {
    console.log(`to:${to.fullPath}`);
    console.log(`from:${from.fullPath}`);

    const toRouteName = to.name || "";
    const toRoutePath = to.fullPath || "";
    console.log(`toRouteName:${toRouteName.toString()}`);
    if (NOT_FOUND_ROUTER === toRouteName.toString()) {
      next();
      return;
    }

    const userToken: string =
      window.localStorage.getItem(TOKEN_SESSION_KEY) || "";

    const isIgnoreRoute = IGNORE_AUTH_ROUTES.includes(toRouteName.toString());
    if (isIgnoreRoute) {
      console.log("isIgnoreRoute");
      // 不需登录的路由
      if (userToken) {
        next({
          name: "dashboard",
        });
      } else {
        next();
      }
    } else {
      // 需要登录的路由
      if (userToken) {
        if (IGNORE_PERMISSION_ROUTES.includes(toRouteName.toString())) {
          next();
        } else {
          const roleMenusStr = window.localStorage.getItem(ROLE_MENU_KEY) || "";
          let roleMenus: RoleMenuVO[] = [];
          try {
            roleMenus = JSON.parse(roleMenusStr);
          } catch (ex) {}
          const targetIndex = roleMenus.findIndex(
            (item) => item.url === toRoutePath
          );
          if (targetIndex >= 0) {
            // 有访问权限
            next();
          } else {
            // 没有访问权限
            next({
              name: "notAuthorized",
            });
          }
        }
      } else {
        next({
          name: "login",
        });
      }
    }
  });
}
